<template>
  <el-card class="content">
    <template #header>
      <div class="header__wrap">
        <el-page-header content="详情页面" @back="goback"></el-page-header>
        <div v-show="projectLeader">
          <el-button @click="goback">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </div>
    </template>
    <div class="project-list-container flex flexColum paddingTop0">
      <!-- <div class="list-h align-center">
        <h4>
          <p class="go-back" @click="goback">
            <i class="el-icon-arrow-left"></i>
            <span>主计划管理</span>
          </p>
          <el-divider direction="vertical"></el-divider>
          <span v-if="route.params.isEdit === 'true'"
            >编辑计划-{{ route.params.item }}</span
          >
          <span v-else-if="route.params.isEdit === 'false'"
            >查看计划-{{ route.params.item }}</span
          >
          <span v-else>添加计划</span>
        </h4>
        <div v-if="!(route.params.isEdit === 'false')">
          <el-button class="add-option" @click="goback">取消</el-button>
          <el-button type="primary" class="add-option" @click="handleSave"
            >保存</el-button
          >
        </div>
      </div> -->
      <div>
        <el-form
          :inline="true"
          :model="formInline"
          class="demo-form-inline"
          :rules="rules"
          ref="formInlineRef"
        >
          <el-form-item label="进度编号">
            <el-input
              v-model.trim="formInline.billNum"
              disabled
              placeholder="进度编号"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item label="进度名称">
            <el-input
              v-model="formInline.billNum"
              disabled
              placeholder="进度名称"
            ></el-input>
          </el-form-item> -->
          <el-form-item label="填报人" prop="filledByName">
            <!-- <el-select-v2
              v-model="formInline.filledById"
              filterable
              :options="userList"
              placeholder="请选择人员"
              style="width: 240px"
              disabled
            >
            </el-select-v2> -->
            <el-input
              v-model.trim="formInline.filledByName"
              disabled
              placeholder="填报人"
            ></el-input>
          </el-form-item>
          <el-form-item label="填报日期">
            <el-date-picker
              v-model="formInline.filledTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="自动填充"
              disabled
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="合同名称" prop="projectManageId">
            <!-- <el-input
              v-model="formInline.projectManageName"
              placeholder="合同名称"
              clearable
            >
              <template #append>
                <el-button
                  icon="el-icon-plus"
                  @click="handleOpenProject"
                ></el-button>
              </template>
            </el-input> -->
            <el-select
              v-if="projectLeader"
              v-model="formInline.projectManageId"
              @change="handleChangeProject"
              :disabled="!projectLeader"
            >
              <!-- value-key="contractId" -->
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.projectName"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-input v-else v-model="formInline.projectManageName" disabled>
            </el-input>
          </el-form-item>
          <el-form-item label="计划开始日期" prop="planStartTime">
            <el-date-picker
              v-model="formInline.planStartTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择日期"
              @change="dateStartChange"
              :disabled="!projectLeader"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="计划结束日期" prop="planEndTime">
            <el-date-picker
              v-model="formInline.planEndTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择日期"
              @change="dateEndChange"
              :disabled="!projectLeader"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="审批状态" prop="approvalStatusCode">
            <el-select
              v-model="formInline.approvalStatusCode"
              placeholder="审批状态"
              class="width-custom120"
              :disabled="!projectLeader"
            >
              <el-option label="未提交" value="0"></el-option>
              <el-option label="待审批" value="1"></el-option>
              <el-option label="已审批" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <!-- <el-form
        :model="formInline"
        :rules="formRules"
        ref="formInline2Ref"
        label-width="120px"
      >
        <el-form-item label="进度管理小组" prop="ProcessGroup">
          <el-input
            v-model="formInline.ProcessGroup"
            placeholder="进度管理小组"
            class="width-custom200"
          >
            <template #append>
              <el-button
                icon="el-icon-plus"
                @click="dialogVisible = true"
              ></el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="进度保障措施" prop="ProcessAccess">
          <el-upload
            :action="uploadUrl"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
            :on-success="
              (res, file, fileList) =>
                uploadSuccess(res, file, fileList, 'ProcessAccess')
            "
            :limit="10"
            :file-list="formInline.ProcessAccess"
          >
            <el-button
              size="small"
              type="primary"
              v-if="!(route.query.isEdit === 'false')"
              >点击上传</el-button
            >
          </el-upload>
        </el-form-item>
        <el-form-item label="其他说明附件">
          <el-upload
            :action="uploadUrl"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
            :on-success="
              (res, file, fileList) =>
                uploadSuccess(res, file, fileList, 'OtherFiles')
            "
            :limit="10"
            :file-list="formInline.OtherFiles"
          >
            <el-button
              size="small"
              type="primary"
              v-if="!(route.query.isEdit === 'false')"
              >点击上传</el-button
            >
          </el-upload>
        </el-form-item>
        <el-form-item label="风险分析">
          <el-input
            v-model="formInline.Risk"
            type="textarea"
            placeholder="请输入内容"
            maxlength="300"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formInline.Mark"
            type="textarea"
            placeholder="请输入内容"
            maxlength="300"
            show-word-limit
          />
        </el-form-item>
      </el-form> -->
      <div v-if="route.query.id">
        <div v-show="projectLeader">
          <el-button
            type="primary"
            @click="taskEditVisible = true"
            v-auth="`/process/main/detail--repeatTask`"
            >创建循环任务</el-button
          >
        </div>
      </div>
      <br />
      <Gantt
        v-if="isGanttView"
        :key="route.path"
        class="gantt-box"
        :tasks="tasks"
        :projectLeader="projectLeader"
        :isDataLength="isDataLength"
        @getGanttData="getGanttData"
        @emitSaveToGo="onSaveToGo"
        ref="mainGanttRef"
      />
    </div>
    <!-- <el-dialog title="选择管理小组" v-model:visible="dialogVisible" width="30%">
      <el-tree
        :data="groupData"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="treeRef"
        highlight-current
        :props="defaultProps"
      ></el-tree>
      <template #fotter>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="getCheckedKeys">确 定</el-button>
        </span>
      </template>
    </el-dialog> -->
  </el-card>
  <task-edit
    :visible="taskEditVisible"
    :projectProgressId="route.query.id"
    @onClose="handleTaskEditClose"
    @onSave="handleTaskEditSave"
  />
</template>

<script lang="ts">
// import { Component, Vue } from "vue-property-decorator";
import { defineComponent, ref, reactive, toRefs, unref, onMounted } from "vue";
import Gantt from "../../Gantt.vue";
import TaskEdit from "../components/taskEdit.vue";
import { useRoute, useRouter } from "vue-router";
// import dataJson from "../../data.json";
// import { GROUP_DATA } from "/@/utils/globalConstant";
import {
  postAddProgress,
  postProgressInfo,
  postUpdateProgress,
  postGetProjectInfo
} from "/@/api/flowProgress";
// import { postProjectTree } from "/@/api/acceptance";
// import { getUserList } from "/@/api/user";
import NotifMessage from "/@/utils/message/notification";
import { storageLocal } from "/@/utils/storage";
import dayjs from "dayjs";

// import request from '@/utils/request'
// @Component({
//   name: "ProcessAdd",
//   components: {
//     Gantt
//   }
// })

export default defineComponent({
  components: {
    Gantt,
    TaskEdit
  },
  setup() {
    let isGanttView = ref(false);
    let projectLeader = ref(true);
    let isDataLength = ref(false);
    const route = useRoute();
    const router = useRouter();
    const formInlineRef = ref<HTMLFormElement | null>(null) as any;
    const formInline2Ref = ref<HTMLFormElement | null>(null) as any;
    const treeProjectRef = ref<HTMLElement | null>(null) as any;
    const mainGanttRef = ref<HTMLElement | null>(null) as any;

    let projectList = ref([]);
    // let userList = ref([]);
    let state = reactive({
      // dialogVisibleProject: false,
      taskEditVisible: false,
      // dialogVisible: false,
      // groupData: GROUP_DATA,
      // uploadUrl: process.env.VUE_APP_BASE_API + "/file/upload",
      // uploadUrl: "/file/upload",
      formInline: {
        billNum: "",
        filledById: "",
        filledByName: "",
        filledTime: "",
        projectManageId: "",
        projectManageName: "",
        planStartTime: "",
        planEndTime: "",
        progressManageUsers: [],
        approvalStatusCode: "",
        progressGanttChart: ""
      }
    });

    let cacheProjectInfo = reactive({
      projectManageId: "",
      projectManageName: ""
    });

    const rules = {
      filledByName: [
        { required: true, message: "请填写姓名", trigger: "blur" }
      ],
      // filledTime: [
      //   { required: true, message: "请填写日期", trigger: "change" }
      // ],
      projectManageId: [
        { required: true, message: "请选择项目", trigger: "change" }
      ],
      planStartTime: [
        { required: true, message: "请填写日期", trigger: "change" }
      ],
      planEndTime: [
        { required: true, message: "请填写日期", trigger: "change" }
      ],
      approvalStatusCode: [
        { required: true, message: "请选择状态", trigger: "change" }
      ]
    };

    const defaultProps = {
      children: "children",
      label: "projectName",
      id: "id"
    };

    const formRules = {
      DateStart: [{ required: true, message: "请选择区域", trigger: "change" }],
      DateEnd: [{ required: true, message: "请选择区域", trigger: "change" }],
      ProcessGroup: [
        { required: true, message: "请输入管理小组名称", trigger: "blur" },
        { min: 3, max: 30, message: "长度在 3 到 30 个字符", trigger: "blur" }
      ],
      ProcessAccess: [
        { required: true, message: "请上传进度保障措施附件", trigger: "blur" }
      ]
    };

    if (!route?.query?.id) {
      isGanttView.value = true;
    }

    const tasks: any = reactive({
      data: [],
      links: []
    });

    // watch(
    //   tasks,
    //   newVal => {
    //     // console.log(newVal);
    //   },
    //   { deep: true }
    // );
    const fileList = ref([]);

    const goback = () => {
      router.push("/projectsS/process/main");
    };

    const dateStartChange = () => {
      const { planStartTime, planEndTime } = state.formInline;
      if (new Date(planStartTime).getTime() > new Date(planEndTime).getTime()) {
        NotifMessage.error("开始时间不能大于结束时间");
      }
    };

    const dateEndChange = () => {
      const { planStartTime, planEndTime } = state.formInline;
      if (new Date(planStartTime).getTime() > new Date(planEndTime).getTime()) {
        NotifMessage.error("结束时间不能晚于开始时间");
      }
    };

    const handleCheckChange = () => {
      const res = treeProjectRef.value.getCurrentNode();
      cacheProjectInfo.projectManageId = [res][0].id;
      cacheProjectInfo.projectManageName = [res][0].projectName;
    };

    //  选择项目事件
    const handleChangeProject = e => {
      const currentItem = projectList.value.filter(item => {
        return item.id === e;
      });
      if (currentItem.length) {
        state.formInline.projectManageName = currentItem[0].projectName;
      }
    };

    // 获取项目信息
    const getProjectList = async (obj: object = {}) => {
      try {
        const { code, data } = await postGetProjectInfo(obj);
        if (code === 200) {
          projectList.value = data;
        }
      } catch (err) {
        console.log(err);
      }
    };

    // async function getUserSelectList(obj: object = {}) {
    //   try {
    //     const { code, data } = await getUserList(obj);
    //     if (code === 200) {
    //       userList.value = data.list.map(item => {
    //         return {
    //           value: item.id,
    //           label: `${item.name}  ${item.companyName}`,
    //           name: item.name
    //         };
    //       });
    //     }
    //   } catch (err) {
    //     console.log(err);
    //   }
    // }

    // // 查询用户名称
    // const searchUserName = (id, userList) => {
    //   const filterData = userList.filter(item => {
    //     return id === item.value;
    //   });
    //   return filterData[0].name;
    // };

    const handleExceed = (files: any, fileList: Array<any>) => {
      // this.$message.warning(
      //   `当前限制选择 10 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
      //     files.length + fileList.length
      //   } 个文件`
      // );
      alert(
        `当前限制选择 10 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    };

    const handleRemove = (files: any, fileList: Array<any>) => {
      console.log(files, fileList);
    };

    const uploadSuccess = (
      res: any,
      files: any,
      fileList: Array<any>,
      filekey?: string
    ) => {
      if (filekey) {
        state.formInline[filekey].push(res.data[0]);
      }
    };

    const handleSave = async () => {
      try {
        const { query } = unref(route);
        const isValid = await new Promise(resolve =>
          formInlineRef.value.validate(resolve)
        );
        if (!isValid) return;
        // 获取甘特图的数据
        getGanttStore();
        // state.formInline.filledByName = searchUserName(
        //   state.formInline.filledById,
        //   userList.value
        // );

        console.log(
          state.formInline.progressGanttChart,
          "state.formInline.progressGanttChart"
        );
        const ganttJson = JSON.parse(state.formInline.progressGanttChart);
        // 如果没有甘特数据就不让保存
        if (!ganttJson.tasks.length) {
          NotifMessage.error("请导入或者添加甘特图数据！");
          return;
        }
        if (!query?.id) {
          const dateTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
          state.formInline.filledTime = dateTime;
        }
        const params = {
          ...state.formInline
        };

        if (route?.query?.id) {
          // 编辑时，不需要提交甘特图数据
          if (params.progressGanttChart !== "") {
            params.progressGanttChart = "";
          }
          const { code, message } = await postUpdateProgress(params);
          commonBackFn(code, message);
        } else {
          const { code, message } = await postAddProgress(params);
          commonBackFn(code, message);
        }
      } catch (err) {
        console.log(err);
      }
    };

    const commonBackFn = (code: Number, message: String) => {
      if (code === 200) {
        NotifMessage.success("添加成功");
        goback();
      } else {
        if (!message) return;
        NotifMessage.error(message);
      }
    };

    // 甘特图内调用，保存页面数据并进行跳转
    const onSaveToGo = async currentGanttId => {
      console.log("跳转");
      // 获取甘特图的数据
      getGanttStore();
      if (!route.query?.id) {
        const dateTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
        state.formInline.filledTime = dateTime;
      }
      const params = {
        ...state.formInline
      };

      if (route?.query?.id) {
        const { code, message } = await postUpdateProgress(params);
        ganttCommonBackFn(code, message, currentGanttId);
      } else {
        const { code, message } = await postAddProgress(params);
        ganttCommonBackFn(code, message, currentGanttId);
      }
    };

    const ganttCommonBackFn = (
      code: Number,
      message: String,
      currentGanttId: any
    ) => {
      if (code === 200) {
        NotifMessage.success("添加成功");
        router.replace({
          path: "/projectsS/acceptance/arrival/detail", // ???????
          query: {
            mode: "add",
            nodeDefId: "ACT_010",
            ganttTaskId: currentGanttId
          }
        });
      } else {
        if (!message) return;
        NotifMessage.error(message);
      }
    };

    // onMounted(() => {
    //   console.log(mainGanttRef.value, "onMounted");
    // });
    // watch(mainGanttRef.value, newVal => {
    //   console.log(newVal, "test");
    // });

    const getGanttData = val => {
      state.formInline.progressGanttChart = JSON.stringify(val);
    };

    const getGanttStore = () => {
      mainGanttRef.value.getGantDatastore();
      // console.log(mainGanttRef.value, "ttttttttt");
    };

    // 获取详情
    const getDataDetialInfo = async () => {
      try {
        const { query } = unref(route);
        if (!query?.id) return;
        const params = {
          id: query?.id
        };
        const { code, data } = await postProgressInfo(params);
        if (code === 200) {
          state.formInline = data;
          tasks.data = JSON.parse(data.progressGanttChart).tasks;
          tasks.links = JSON.parse(data.progressGanttChart).links;
          isGanttView.value = true;
          projectLeader.value = data.projectLeader;

          const ganttJson = JSON.parse(data.progressGanttChart);

          if (ganttJson.tasks.length) {
            isDataLength.value = true;
          } else {
            isDataLength.value = false;
          }
        }
      } catch (err) {
        console.log(err);
      }
    };

    const handleTaskEditClose = () => {
      console.log("false");
      state.taskEditVisible = false;
    };

    const handleTaskEditSave = () => {
      state.taskEditVisible = false;
    };

    // getUserSelectList({
    //   pageNum: 1,
    //   pageSize: 10000
    // });

    onMounted(() => {
      const { query } = unref(route);
      if (!query?.id) {
        const { name, userId } = storageLocal.getItem("info");
        state.formInline.filledByName = name;
        state.formInline.filledById = userId;
      }
      getDataDetialInfo();
    });
    getProjectList();

    return {
      ...toRefs(state),
      isGanttView,
      projectList,
      // userList,
      mainGanttRef,
      formInlineRef,
      formInline2Ref,
      treeProjectRef,
      rules,
      defaultProps,
      formRules,
      tasks,
      fileList,
      route,
      projectLeader,
      isDataLength,
      goback,
      dateStartChange,
      dateEndChange,
      handleExceed,
      handleRemove,
      uploadSuccess,
      handleSave,
      getGanttData,
      getGanttStore,
      handleCheckChange,
      ganttCommonBackFn,
      onSaveToGo,
      handleTaskEditClose,
      handleTaskEditSave,
      handleChangeProject
    };
  }
});
</script>
<style lang="scss" scoped>
.content {
  .header__wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  :deep .el-card__header {
    padding: 10px 10px;
  }
}
.project_dialog {
  max-height: 40vh;
  overflow-y: auto;
}

.el-tree :deep .is-current .el-tree-node__label {
  color: #409eff;
  font-weight: 700;
}
.el-tree :deep .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}
</style>
